package cn.lj.security;

import cn.hutool.core.util.StrUtil;
import cn.lj.entity.User;
import cn.lj.service.UserService;
import cn.lj.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @file:
 * @version:
 * @Description: JWT认证过滤器
 * 通过请求头中获取jwt，然后解析出用户名，知道是谁在访问接口，然后判断用户是否有权限等操作
 * @author: 李津
 * @date: 2021-05-22 11:45
 * 本代码要注意的事项、备注事项等
 */

@Slf4j
public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private UserDetailServiceImpl userDetailService;


    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 过滤器用来进行识别jwt
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info("jwt 校验 filter");
        String jwt = request.getHeader(jwtUtils.getHeader());

        //判断jwt存在
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }

        //判断jwt是否合法
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if (claim == null) {
            throw new JwtException("token异常！");
        }

        //判断jwt是否过期
        if (jwtUtils.isTokenExpired(claim)) {
            throw new JwtException("token已过期");
        }

        //jwt合法
        String username = claim.getSubject();
        log.info("用户-{}，正在登陆！", username);

        //获取用户权限信息
        //获取到用户名之后我们直接把封装成UsernamePasswordAuthenticationToken，之后交给SecurityContextHolder参数传递authentication对象，这样后续security就能获取到当前登录的用户信息了，也就完成了用户认证。
        User user = userService.getByUserName(username);
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(username, null, userDetailService.getUserAuthority(user.getId()));

        SecurityContextHolder.getContext().setAuthentication(token);
        chain.doFilter(request, response);
    }
}
